package com.supplychain.scm.core.feign.interceptor;

import com.supplychain.scm.core.basis.constant.StringPool;
import com.supplychain.scm.core.basis.constant.CommonConstants;
import com.supplychain.scm.core.common.constant.ServiceNameConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Target;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName AbstractGrayFeignInterceptor
 * @Description 灰度版本拦截器设置
 * @createTime 10:06:00 2023/02/11
 */
@Slf4j
public abstract class AbstractGrayFeignInterceptor implements RequestInterceptor {

    protected String projectVersion;

    public AbstractGrayFeignInterceptor() {
        this.projectVersion = versionLoad();
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String applicationName = Optional.of(requestTemplate).map(RequestTemplate::feignTarget).map(Target::name).orElse(StringPool.EMPTY);
        if(StringUtils.isNotBlank(applicationName) && StringUtils.isNotBlank(this.projectVersion) && Objects.equals(this.applycationName(),applicationName)){
            // 设置灰度版本
            requestTemplate.header(CommonConstants.VERSION,this.projectVersion);
        }
    }

    /**
     * 资源路径
     * @see "META-INF/maven/com.duobaoyu/dby-supply-chain-api-remote/pom.properties"
     * @return
     */
    protected abstract String getResourcePattern();

    /**
     * 获取服务名方法
     * @see ServiceNameConstants
     * @return
     */
    protected String applycationName() {
        return StringPool.EMPTY;
    }

    private String versionLoad(){
        Resource[] resources = new Resource[CommonConstants.ZERO];
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + this.getResourcePattern();
        try {
            resources = new PathMatchingResourcePatternResolver().getResources(pattern);
        } catch (IOException e) {
            log.warn("versionLoad error => {}", ExceptionUtils.getStackTrace(e));
        }
        Properties properties = null;
        try {
            properties = PropertiesLoaderUtils.loadProperties(resources[CommonConstants.ZERO]);
        } catch (IOException e) {
            log.warn("versionLoad properties error => {}", ExceptionUtils.getStackTrace(e));
        }
        return Optional.of(properties).map(config -> config.getProperty("version")).orElse(StringPool.EMPTY);
    }
}
